//
//  ForgetpasswordViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/6/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ForgetpasswordViewController.h"
#import "TopBackView.h"
#import "Common.h"
#import "WKProgressHUD.h"


@interface ForgetpasswordViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField *phoneTextField;
@property (nonatomic,strong) UITextField *captchaTextField;
@property (nonatomic,strong) UITextField *passwordField;

@property (nonatomic,strong) UIButton *captchaButton;
@property (nonatomic) NSInteger secondCountDown;

@property (nonatomic) NSInteger integer1;
@property (nonatomic) NSInteger integer2;

@property (nonatomic,strong) WKProgressHUD *hud;


@end

@implementation ForgetpasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"找回密码"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    

    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    [self initSubViews];

}

-(void)initSubViews
{
    
    UILabel *alertLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, screenWidth, 30)];
    alertLabel.text = @"请输入您手机号和短信验证码，并重新设置密码";
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = Font(12);
    alertLabel.backgroundColor = Color_RGB(234, 234, 234, 1);
    [self.view addSubview:alertLabel];
    
    
    self.phoneTextField = [[UITextField alloc]init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入验证码";
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.passwordField = [[UITextField alloc]init];
    self.passwordField.placeholder = @"请输入6-14位数字与字母组合的密码";
    self.passwordField.secureTextEntry = YES;
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    //手机号
    UIView *firstV = [self backViewWithFloat:CGRectGetMaxY(alertLabel.frame) andField:self.phoneTextField  andImage:[UIImage imageNamed:@"register_phone"]];
    
    [self.view addSubview:firstV];
    
    //验证码
    UIView *secondV = [self backViewWithFloat:CGRectGetMaxY(firstV.frame) andField:self.captchaTextField  andImage:[UIImage imageNamed:@"register_capture"]];
    
    [self.view addSubview:secondV];
    
    
    //密码
    UIView *thirdV = [self backViewWithFloat:CGRectGetMaxY(secondV.frame) textFieldPass:self.passwordField andImage:[UIImage imageNamed:@"register_password"]];
    

    
    [self.view addSubview:thirdV];
    
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.captchaButton.frame = CGRectMake(screenWidth - 100 * kWidth, (cellHeight - 23)/2.0, 75 * kWidth, 23 * kHeight);
    [self.captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    self.captchaButton.backgroundColor = Color_RGB(253, 243, 232, 1);
    [self.captchaButton addTarget:self action:@selector(captchaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.captchaButton.titleLabel.font = Font(12);
    self.captchaButton.layer.cornerRadius = 5;
    self.captchaButton.layer.borderColor = YellowColor.CGColor;
    self.captchaButton.layer.borderWidth = 0.5;
    
    [firstV addSubview:self.captchaButton];
    
    
    
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(18 , CGRectGetMaxY(thirdV.frame) + 30 * kHeight, screenWidth - 36, Button_Height);
    agreeButton.titleLabel.font = Font(17);
    agreeButton.backgroundColor = YellowColor;
    agreeButton.layer.cornerRadius = 5;
    [agreeButton setTitle:@"确 定" forState:UIControlStateNormal];
    [agreeButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [self.view addSubview:agreeButton];
     [agreeButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view addGestureRecognizer:tap];

   
   
}

-(void)tap
{
    [self.view endEditing:YES];
}


//确认信息 并返回上一页面
-(void)confirmButton
{
//    1、确认信息
    
    if (self.phoneTextField.text.length <= 0 || self.captchaTextField.text.length <= 0 || self.passwordField.text.length <= 0) {
        
        [WKProgressHUD popMessage:@"请将信息填写完整" inView:self.view duration:1.5 animated:YES];

//        [self showAlertWithString:@"请将信息填写完整" andInteget:0];
    } else {
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    NSString *urlString = [NSString stringWithFormat:@"%@login/resetpwd",Main_interface];
    
    NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                          @"password":self.passwordField.text,
                          @"usertype":@"40",
                          @"authcode":self.captchaTextField.text};
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
        
        [self.hud dismiss:YES];
        
        NSDictionary *dictionry = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dictionry[@"message"]  inView:self.view duration:1.5 animated:YES];

        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if ([dictionry[@"success"] boolValue]) {
                
                //            [self showAlertWithString:dictionry[@"message"] andInteget:1];
                
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                
                [WKProgressHUD popMessage:dictionry[@"message"]  inView:self.view duration:1.5 animated:YES];
                
            }
            
        });
        

        
        
    } failedBlock:^(NSString *errorMsg) {
        [self.hud dismiss:YES];
        NSLog(@"%@",errorMsg);
    }];
        
    }
    
    
//    //延迟执行
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        //2、返回
//        [self backAction];
//        
//    });
    
}


-(UIView *)backViewWithLabelString:(NSString *)string andTextField:(UITextField *)field andInteger:(NSInteger)integer
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 104 + 40 * integer, screenWidth, 40)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 5, 130 * kWidth, 30)];
    label.text = string;
    label.font = Font(15);
    
    [view addSubview:label];
    
    
    field.frame = CGRectMake(CGRectGetMaxX(label.frame), 5, screenWidth - CGRectGetMaxX(label.frame) - 14, 30);
    field.delegate = self;
    field.font = Font(15);
    
    [view addSubview:field];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(view.frame) - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    
    return view;
}


-(void)showAlertWithString:(NSString *)string andInteget:(NSInteger)integet
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1   = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2   = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
    if (integet == 1) {
       
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        });

    }
    
   
    
}


-(UIView *)backViewWithFloat:(CGFloat)y andField:(UITextField *)textField andImage:(UIImage *)image
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(28 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 200, view.frame.size.height);
    textField.font = Font(12);
    [view addSubview:textField];
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;

    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, view.frame.size.height - 0.5, screenWidth - 36, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}


-(UIView *)backViewWithFloat:(CGFloat)y textFieldPass:(UITextField *)textFieldPass andImage:(UIImage *)image
{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(28 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textFieldPass.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 130, view.frame.size.height);
    textFieldPass.font = Font(12);
    [view addSubview:textFieldPass];
    textFieldPass.delegate = self;
    textFieldPass.returnKeyType = UIReturnKeyDone;
    
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, view.frame.size.height - 0.5, screenWidth - 36, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}





-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
    
//    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark 验证码方法
-(void)captchaButtonAction:(UIButton *)sender
{
    
        //先判断手机号的正确
        NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
        BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
        if (isRight) {
    
       
    NSString *urlString = [NSString stringWithFormat:@"%@login/resetcaptcha",Main_interface];
    NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                          @"usertype":@"40"};
    

    Common *c = [[Common alloc]init];
    
    [ c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        [WKProgressHUD popMessage:dict[@"message"] inView:self.view duration:1.5 animated:YES];

        if ([dict[@"success"] boolValue]) {
            
            [sender setTintColor:WhiteColor];
            sender.userInteractionEnabled = NO;
            _secondCountDown = 120;
            NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
            [time fire];

        }
        
    } failedBlock:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
        
    }];
    
     
        } else {
    
            [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];

        }
    
}

-(void)timeFireAction:(NSTimer *)time
{
    _secondCountDown --;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%lds)",_secondCountDown]];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
    
    
    if (_secondCountDown <= 0) {
        [time invalidate];
        self.captchaButton.userInteractionEnabled = YES;
        //设置button下划线
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"重新发送"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
        //        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        
        [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
        
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForeground:) name:@"foreground" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackground:) name:@"background" object:nil];
    
    self.navigationController.navigationBarHidden = YES;

}

- (void)appGoBackground:(NSNotification *)notification
{
    
    _integer1 = [notification.userInfo[@"time"] integerValue];
    
}

- (void)appGoForeground:(NSNotification *)notification
{
    NSInteger integer = [notification.userInfo[@"time"] integerValue];
    
    _integer2 = (integer - _integer1)/1000;
    
    _secondCountDown = _secondCountDown - _integer2;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


#pragma mark UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
